import { DateObject } from '../types/common';
import { UseMonth } from './types';

export function useMonth(): UseMonth {
    function daysInMonth(month: number, year: number): number {
        return new Date(year, month, 0).getDate();
    }

    function getDate(year: number, month: number, day: number): Date {
        // Creates a date object from given year, month and day
        return new Date(year, month - 1, day, 0, 0, 0, 0);
    }

    function daysInPreMonth(month: number, year: number): number {
        // Return number of days of the previous month
        const date: Date = getDate(year, month, 1);
        date.setMonth(date.getMonth() - 1);
        return daysInMonth(date.getMonth() + 1, date.getFullYear());
    }

    function getNextMonth(month: number, year: number): DateObject {
        const nextMonthDate = {
            year: month === 12 ? year + 1 : year
        } as DateObject;
        const nextMonth = month === 12 ? 1 : month + 1;
        nextMonthDate.month = nextMonth;
        return nextMonthDate;
    }

    function getPreviousMonth(month: number, year: number): DateObject {
        const previousMonthDate = {
            year: month === 1 ? year - 1 : year
        } as DateObject;
        const previousMonth = month === 1 ? 12 : month - 1;
        previousMonthDate.month = previousMonth;
        return previousMonthDate;
    }

    return { daysInMonth, daysInPreMonth, getNextMonth, getPreviousMonth };
}
